use cpal::traits::{DeviceTrait, HostTrait, StreamTrait};
use ringbuf::{HeapRb, Consumer};
use std::sync::Arc;
use std::time::Duration;
use std::thread;

// 音频录音器结构体（简化版本）
struct AudioRecorder {
    _stream: cpal::Stream,
    consumer: Consumer<f32, Arc<HeapRb<f32>>>,
    target_sample_rate: u32,
}

impl AudioRecorder {
    fn new(target_sample_rate: u32) -> Result<Self, Box<dyn std::error::Error>> {
        let host = cpal::default_host();
        let device = host.default_input_device()
            .ok_or("没有找到默认音频输入设备")?;
        
        let config = device.default_input_config()
            .map_err(|e| format!("无法获取默认音频输入配置: {}", e))?;
        
        println!("麦克风设备: {}, 配置: {:?}", device.name()?, config);
        
        let input_sample_rate = config.sample_rate().0;
        let input_channels = config.channels();
        
        println!("麦克风配置: {}Hz, {}通道", input_sample_rate, input_channels);
        println!("目标配置: {}Hz", target_sample_rate);

        // 创建环形缓冲区用于音频数据
        let ring_buffer = HeapRb::<f32>::new((input_sample_rate as f32 * 0.5) as usize); // 2秒的缓冲区
        let (mut producer, consumer) = ring_buffer.split();
        
        let stream = device.build_input_stream(
            &config.into(),
            move |data: &[f32], _: &cpal::InputCallbackInfo| {
                for &sample in data {
                    if let Err(_) = producer.push(sample) {
                        println!("麦克风缓冲区已满，丢弃音频数据");
                        break;
                    }
                }
            },
            |err| eprintln!("麦克风录音错误: {}", err),
            None,
        )?;
        
        stream.play()?;
        
        Ok(AudioRecorder {
            _stream: stream,
            consumer,
            target_sample_rate,
        })
    }
    
    /// 从麦克风读取音频数据
    fn read_audio(&mut self) -> Vec<f32> {
        let mut samples = Vec::new();
        
        // 读取可用的音频数据
        while let Some(sample) = self.consumer.pop() {
            samples.push(sample);
        }
        
        samples
    }
}

fn main() -> Result<(), Box<dyn std::error::Error>> {
    println!("开始测试麦克风录音功能...");
    
    // 创建音频录音器
    let mut audio_recorder = AudioRecorder::new(8000)?;
    println!("音频录音器初始化完成");
    
    // 录音测试循环
    let mut test_count = 0;
    loop {
        thread::sleep(Duration::from_millis(100)); // 100ms间隔
        
        let audio_samples = audio_recorder.read_audio();
        if !audio_samples.is_empty() {
            test_count += 1;
            
            // 计算音频数据的统计信息
            let min_sample = audio_samples.iter().fold(f32::INFINITY, |a, &b| a.min(b));
            let max_sample = audio_samples.iter().fold(f32::NEG_INFINITY, |a, &b| a.max(b));
            let avg_sample = audio_samples.iter().sum::<f32>() / audio_samples.len() as f32;
            
            println!("测试 {}: 读取到 {} 个样本, 范围: [{:.4}, {:.4}], 平均值: {:.4}", 
                    test_count, audio_samples.len(), min_sample, max_sample, avg_sample);
            
            // 如果检测到有意义的音频（非静音），显示更多信息
            if (max_sample - min_sample).abs() > 0.01 {
                println!("  检测到音频活动！");
            }
        }
        
        // 运行10秒后退出
        if test_count >= 100 {
            println!("测试完成，共进行了 {} 次录音测试", test_count);
            break;
        }
    }
    
    Ok(())
}
